﻿using SelfMeter.Data;
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using System.Linq;

namespace SelfMeter
{
    public partial class Editing : UserControl, ISelfMeterView
    {
        private MeterDefinition _meter;

        private MeterItem _newMeterItem = null;

        private ObservableCollection<MeterItem> _dataSource = null;

        class MeterItemConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, string language)
            {
                if (value is DateTime)
                {
                    DateTime d = (DateTime)value;
                    return d == DateTime.MinValue ? string.Empty : d.ToString("g");
                }
                else if (value is Double)
                {
                    double d = (double)value;
                    return d == double.MinValue ? string.Empty : value;
                }

                throw new ArgumentException("Unexpected value type");
            }

            public object ConvertBack(object value, Type targetType, object parameter, string language)
            {
                throw new NotImplementedException();
            }
        }

        public Editing(MeterDefinition md)
        {
            InitializeComponent();
            _meter = md;
            // populate edit grid
            Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(PopulateEditGrid));
            // store sample description in Tag property
            this._data.Minimum = 0;
            
        }

        private void PopulateEditGrid()
        {
            // create the data
            _dataSource = new ObservableCollection<MeterItem>(_meter.MeterData);
            _name.Text = _meter.Name;
            _description.Text = _meter.Description;
            _unit.Text = _meter.Unit;

            NewItem();
            AttachSource();
            _flexEdit.IsReadOnly = true;
            _flexEdit.SelectionMode = C1.Xaml.FlexGrid.SelectionMode.RowRange;
            foreach (var col in _flexEdit.Columns)
            {
                col.HorizontalAlignment = HorizontalAlignment.Center;
                col.VerticalAlignment = VerticalAlignment.Center;
                col.Width = new GridLength(180);
                col.ValueConverter = new MeterItemConverter();
            }

        }

        private void NewItem()
        {
            _newMeterItem = new MeterItem { Data = double.MinValue, Date = DateTime.MinValue };
            _dataSource.Add(_newMeterItem);
        }

        private void AttachSource()
        {
            if (_dataSource.Count > 0)
            {
                var view = new CollectionViewSource();
                view.Source = _dataSource;

                _flexEdit.ItemsSource = view.View;
                //_flexEdit.ItemsSource = _dataSource;
            }
        }

        private async void OnSave(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(_name.Text))
            {
                ShowErrorMessage("Name can not be empty");
                return;
            }

            _meter.Name = _name.Text;
            _meter.Description = _description.Text;
            _meter.Unit = _unit.Text;
            
            var ret = await SelfMeterDataSource.SaveMeterData(_meter);
            if (!ret)
            {
                ShowErrorMessage("Can not save your data");
            }
            else
            {
                ShowNotification("Your data has been saved successfully");
            }
        }

        private void OnAdd(object sender, RoutedEventArgs e)
        {
            Debug.Assert(_newMeterItem != null);
            if (_date.DateTime == null)
            {
                ShowErrorMessage("Please select a date");
                return;
            }

            DateTime date = (DateTime)_date.DateTime;

            var repeat = _meter.MeterData.Count((mi) => { return mi.Date == date; });
            if (repeat > 0)
            {
                ShowErrorMessage("can't input repeated date");
                return;
            }

            _newMeterItem.Data = _data.Value;
            _newMeterItem.Date = date;
            
            _meter.MeterData.Add(_newMeterItem);
            NewItem();
        }

        private void OnDelete(object sender, RoutedEventArgs e)
        {
            var selected = _flexEdit.SelectedItems;
            if (selected != null)
            {
                if (selected.Count > 0)
                {
                    var items = new MeterItem[selected.Count];
                    selected.CopyTo(items, 0);
                    foreach (var mi in items)
                    {
                        _meter.MeterData.RemoveAll((o) => o.Date == mi.Date);
                        if (mi != _newMeterItem)
                        {
                            _flexEdit.CollectionView.Remove(mi);
                            _flexEdit.SelectedItems.Clear();
                            _flexEdit.CollectionView.MoveCurrentToNext();
                        }
                    }
                }
            }

        }

        private void ShowErrorMessage(string message)
        {
            var mb = new MessageDialog(message, "Error");
            mb.ShowAsync();
        }

        private void ShowNotification(string message)
        {
            var mb = new MessageDialog(message, "Notification");
            mb.ShowAsync();
        }

        public void UpdateView(MeterDefinition meter, bool load)
        {
            _meter = meter;
            if (load)
                PopulateEditGrid();
        }

        
    }
}
